<?php
namespace app\admin\controller;

use think\Session;
use app\common\controller\AdminBase;
use app\common\model\WxUser as WxUserModel;
use app\common\util\WechatThirdUtil;

class SourceMaterial extends AdminBase
{
    protected $wechat_obj;
    protected $config;
    protected $wechat_author_config;
    protected $wx_user_model;
    protected function _initialize(){
        parent::_initialize();
        $this->wx_user_model = new WxUserModel;
        $this->config = $this->wx_user_model->find();
        $this->wechat_author_config = session::get('wechat_info');
        $this->wechat_obj = new WechatThirdUtil($this->config , $this->wechat_author_config);
    }

    public function index(){
        return $this->fetch();
    }

    /**
     * 获取素材列表
     */
    public function getMaterial($type,$offset = 0,$count = 20){
        $news = [];
        $offset2 = $offset;
        $result = $this->wechat_obj->getMaterialList($type,$offset,$count);
        if(!$result){
            return json(['status' => -1,'msg' => '参数错误','item' => '']);
        }else{
            if($result['total_count'] > $result['item_count']){
                $total_page = $result['total_count'] / $result['item_count'];
                for($i = 0;$i < $total_page;$i++){
                    $offset2 += $offset + $count;
                    $result2= $this->wechat_obj->getMaterialList($type,$offset2,$count);
                    $news[] = $result2['item'];
                }
            }else{
                $news = $result['item'];
            }
            return json(['status' => 1,'msg' => '获取成功','item' => $news]);
        }
    }

    /**
     * 获取图文素材详情
     */
    public function getMaterialDetail($media_id){
        $result = $this->wechat_obj->getMaterial($media_id);
        if(!$result){
            return json(['status' => -1,'msg' => 'media_id错误','item' => '']);
        }
        return json(['status' => -1,'msg' => '获取成功','item' => $result['news_item']]);
    }

    /**
     * 修改永久素材
     */
    public function updateMaterial(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $media_id = $data['media_id'];
            $article = $data['article'];
            $index = isset($data['index']) ? $data['index'] : 0;
            $result = $this->wechat_obj->updateNews($media_id , $article , $index = 0);
            if($result){
                return json(['status' => 1 , 'msg' => '修改成功']);
            }else{
                return json(['status' => -1 , 'msg' => '修改失败']);
            }
        }
    }

    /**
     * 删除永久素材，包括图文
     */
    public function deleteMaterial($media_id){
        $result = $this->wechat_obj->delMaterial($media_id);
        if($result){
            return json(['status' => 1 , 'msg' => '删除成功']);
        }else{
            return json(['status' => 1 , 'msg' => '删除失败']);
        }
    }
}